﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SampleEquityPairStrategyModel.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Org.OpenTrader.Framework.Enums;
using Org.OpenTrader.Framework.Forge.Enums;
using Org.OpenTrader.Framework.Forge.Events;
using Org.OpenTrader.Framework.Forge.Interfaces;
using Org.OpenTrader.Framework.LiveObjects;
using Org.OpenTrader.Framework.LiveObjects.Interfaces;

namespace Org.OpenTrader.Framework.Forge.Plugins
{
    [Credits("Yield Pair Trader", "Pair trade working on yield of the spread", "David Sibi","Copyright (C) David Sibi <mailto:david.sibi@systemathics.com>")]
    [ImplementsInterface("Org.OpenTrader.Framework.Forge.Interfaces.IStrategyPlugin")]
    public sealed class WorkingEquityPairStrategyModel : StrategyModel
    {
        private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

        #region Constructors and Destructors

        public WorkingEquityPairStrategyModel(ILiveObjectDescriptor descriptor, ILiveObjectContainer container): base(descriptor, container){}

        #endregion

        #region Properties

        public override string Name
        {
            get
            {
                return "Yield Pair Trader";
            }
        }
        
        /// <summary>
        /// Number of the Strategy Parameters
        /// </summary>
        public override int NbParams
        {
            get { return 0; }
        }

        #endregion

        #region Public Methods

        public override Status Create()
        {
            //// Strategy Model Cell
            //IStrategyModelCell cell = new YieldPairTraderModelCell(this);
            //cell.SetParam("Name", "IBM/DELL");
            //cell.SetParam("StartAt", "09:00:00");
            //cell.SetParam("StopAt", "18:00:00");
            //cell.Add("IBM US Equity");
            //cell.Add("DELL US Equity");
            //Add(cell);
            //Start();
            return Status.Success(Identity);
        }
        public override Status Destroy()
        {
            Stop();
            return Status.Success(Identity);
        }
        public override void OnFeed(object sender, FeedEventArgs args)
        {
        }
        public override void OnOrder(object sender, OrderTrackingEventArgs args)
        {
        }
        public override void Run()
        {
        }
        public override bool SetParam(string key, Table.Cell val)
        {
            return false;
        }

        #endregion

        /// <summary>
        /// Set the strategy cells
        /// </summary>
        /// <returns></returns>
        protected override bool SetCells()
        {
            return false;
        }

        public class YieldPairTraderModelCell : StrategyModelCell
        {
            private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());
            private double Yield_Bid1, Yield_Ask2, Yield_Ask1, Yield_Bid2, Spread_Bid, Spread_Ask, Mid;
            private Bollingers Bollinger = new Bollingers(100, 1.5);

            public event EventHandler<EventArgs> OnIndicator;

            #region Constructors and Destructors

            public YieldPairTraderModelCell(IStrategyModel parent): base(parent)
            {
            }

            #endregion

            #region Public Methods

            public override void OnFeed(object sender, FeedEventArgs args)
            {
                bool CanTrade = false;

                if (args is FeedEventArgs.ConnectionStatus)
                {
                }
                else if (args is FeedEventArgs.MarketBookUpdate)
                {
                    if (this[0].MarketBook.Bids[0].HasValue && this[0].MarketBook.Asks[0].HasValue && this[0].MarketFields[EMarketField.Open].HasValue &&
                        this[1].MarketBook.Bids[0].HasValue && this[1].MarketBook.Asks[0].HasValue && this[1].MarketFields[EMarketField.Open].HasValue)
                        CanTrade = true;

                    if (CanTrade)
                    {
                        Yield_Bid1 = this[0].MarketBook.Bids[0].Price/(double) this[0].MarketFields[EMarketField.Open].Value - 1; //VWAP much better
                        Yield_Ask1 = this[0].MarketBook.Asks[0].Price/(double) this[0].MarketFields[EMarketField.Open].Value - 1;
                        Yield_Bid2 = this[1].MarketBook.Bids[0].Price/(double) this[1].MarketFields[EMarketField.Open].Value - 1;
                        Yield_Ask2 = this[1].MarketBook.Asks[0].Price/(double) this[1].MarketFields[EMarketField.Open].Value - 1;

                        Spread_Bid = Yield_Bid1 - Yield_Ask2;
                        Spread_Ask = Yield_Ask1 - Yield_Bid2;
                        Mid = 0.5*(Spread_Bid + Spread_Ask);

                        Bollinger.Calculate(Mid);// Un petit Bollinger a la va vite PS: pour ceux qui reflechissent deux fois plus vite que la moyenne.
                                                 // Ceux la auront soins de remarquer, que le calcul est recursif.


                        CanTrade = (!Expo[EExpoCellType.Traded].IsLong & !Expo[EExpoCellType.Traded].IsShort) && // c'est ce que je vous disais t'as l'heur au resto sur les expo
                                   (!Expo[EExpoCellType.Working].IsLong & !Expo[EExpoCellType.Working].IsShort) &&// si a chaque fois il faut checker ca, c'est pas tres user friendly
                                   (!Expo[EExpoCellType.Pending].IsLong & !Expo[EExpoCellType.Pending].IsShort);

                        if (CanTrade)
                        {
                            if (Mid >= Bollinger.BBU.Last())
                            {
                                int Qty0 = (int) (50000/(double)this[0].MarketBook.Bids[0].Price); // capital neutral ( 50 000 $ on each)
                                int Qty1 = (int)(50000 / (double)this[0].MarketBook.Bids[0].Price); 
                                this[0].Sell(EOrderType.Limit, this[0].MarketBook.Bids[0].Price, Qty0,Parent.BookingPath);
                                this[1].Buy(EOrderType.Limit, this[1].MarketBook.Asks[0].Price, Qty1, Parent.BookingPath);
                            }
                            else if (Mid <= Bollinger.BBD.Last())
                            {
                                int Qty0 = (int)(50000 / (double)this[0].MarketBook.Bids[0].Price);
                                int Qty1 = (int)(50000 / (double)this[0].MarketBook.Bids[0].Price);
                                this[0].Buy(EOrderType.Limit, this[0].MarketBook.Bids[0].Price, Qty0, Parent.BookingPath);
                                this[1].Sell(EOrderType.Limit, this[1].MarketBook.Asks[0].Price, Qty1, Parent.BookingPath);
                            }
                        }
                    }
                }
            }
            public override void OnOrder(object sender, OrderTrackingEventArgs args)
            {
                Logging.Log(Identity, ELogLevel.Debug, () => string.Format("OnOrder : received {0}", args.ToString()));
            }

            #endregion
            
            /// <summary>
            /// Nb Parameters
            /// </summary>
            public override int NbParams
            {
                get
                {
                    return 0;
                }
            }
        }

        public class Bollingers 
        {
            public List<Double> BBU { get; private set; }
            public List<Double> BBD { get; private set; }

            private readonly int Length;
            private readonly double Sigma;
            private readonly Queue<double> queue;
            private double a, b, c, mu, sigma_squarre, temp;

            public Bollingers(int length, double sigma)
            {
                Length = length;
                Sigma = sigma;

                a = ((double)(Length - 1) / Length);
                b = (1 /(double) Length);
                c = (1 /(double) (Length - 1));
                mu = 0;
                sigma_squarre = 0;
                queue = new Queue<double>();
                BBU = new List<double>();
                BBD = new List<double>();
            }
            public void Calculate(double value)
            {
                if (queue.Count < Length)
                {
                    queue.Enqueue(value);
                    mu = queue.Average();
                }
                else
                {
                    mu = a * mu + b * value;
                    sigma_squarre = a * sigma_squarre + c * Math.Pow(value - mu, 2);
                    temp = Sigma * Math.Sqrt(sigma_squarre);
                    BBU.Add(mu + temp);
                    BBD.Add(mu - temp);
                }
            }
        }
    }
}